import configparser
import os


class OperateConfig:
    def __init__(self):
        self.BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        self.confPath = os.path.join(self.BASE_DIR, 'small_project_test\\config\\config.ini')
        self.cfg = configparser.ConfigParser()
        self.cfg.read(self.confPath, encoding="utf-8-sig")

    def confRead(self, section, option):
        if self.cfg.has_section(section=section):  # 判断节点是否存在
            if self.cfg.has_option(section=section, option=option):  # 判断选项是否存在
                return self.cfg.get(section, option)  # 获取选项的值
            else:
                print(f"选项{option}不存在")
        else:
            print(f"节点{section}不存在")

    def confReadAll(self, section):
        if self.cfg.has_section(section=section):  # 判断节点是否存在
            options = self.cfg.options(section=section)  # 获取节点下所有的选项
            dic = {}
            for option in options:
                optionvalue = self.confRead(section, option=option)  # 将该节点下所有值的存为字典
                dic[option] = optionvalue
            return dic
        else:
            print(f"节点{section}不存在")

    def confWrite(self, section, option, value):
        """
        更新选项的值
        :param section: 节点
        :param option: 选项
        :return:
        """
        if not self.cfg.has_section(section=section):  # 判断节点是否存在
            self.cfg.add_section(section=section)  # 新增节点
        self.cfg.set(section, option, str(value))  # 更新选项的值
        with open(self.confPath, "w+", encoding="utf-8-sig") as f:
            self.cfg.write(f)
